import Event from 'events'

import { mockBigData } from '../MainBoard/Chart/mock'

// import worker from './db-worker'

import cacheBox from './cache-box'

class Controller extends Event {
  timer = null
  timestamp = 0

  initPlayer() {
    this.timer = setInterval(async () => {
      if (this.timestamp > 100) {
        this.timestamp = 0
      }
      this.timestamp++
      // try to get it from cache
      const cacheData = await cacheBox.get(this.timestamp)
      if (cacheData) {
        this.emit('updateChartData', {
          ...cacheData,
          fromCache: true
        })
        return
      }
      // generate a mock data
      const mockData = mockBigData(1024 * 1024)
      // try to update cache
      cacheBox.update({
        timestamp: this.timestamp,
        data: mockData
      })
      this.emit('updateChartData', {
        timestamp: this.timestamp,
        data: mockData,
        fromCache: false
      })
    }, 1000 / 60)
  }

  stopPlayer() {
    if (this.timer) {
      clearInterval(this.timer)

      this.timer = null
    }

    // ;(async () => {
    //   console.log('all cache>>>>>', await cacheBox.getAll())
    // })()
  }

  togglePlayer() {
    if (!this.timer) {
      this.initPlayer()
    } else {
      this.stopPlayer()
    }
  }
}

export default new Controller()
